package com.wx.disparent.mallparent.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wx.disparent.mallparent.commons.inface.IBaseService;
import com.wx.disparent.mallparent.dao.OrderMapper;
import com.wx.disparent.mallparent.dao.ProductMapper;
import com.wx.disparent.mallparent.entity.MerchantEntity;
import com.wx.disparent.mallparent.entity.OrderEntity;
import com.wx.disparent.mallparent.entity.ProductEntity;
import com.wx.disparent.mallparent.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 曾右权
 * @description 订单服务层
 * @date 2019/12/9 19:11
 */

@Service
public class OrderService implements IBaseService<OrderEntity> {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductMapper productMapper;

    /**
     * 查询所有订单（如果params为空，则查询所有订单。）
     *
     * @param params 查询条件（根据1、用户id，2、上级用户id，3、订单id查询）
     * @return List<OrderEntity> 订单信息集合
     */
    public List<OrderEntity> findAll(Map<String, Object> params) {
        return orderMapper.findAll(params);
    }


    /**
     * 通过订单id查询订单信息
     *
     * @param t 订单id
     * @return orderEntity 订单信息
     */
    public OrderEntity findById(int t) {
        return orderMapper.findById(t);
    }

    public OrderEntity findById(String t) {
        OrderEntity orderEntity;
        if (t != null && !t.equals("")) {
            orderEntity = orderMapper.findById(Integer.parseInt(t));
        } else {
            orderEntity = null;
        }
        return orderEntity;
    }

    /**
     * 计算订单实付金额
     *
     * @param productId 商品id
     * @param totalNum  购买数量
     * @return Map<String, Object> order订单信息 product商品信息
     */
    public Map<String, Object> ordergenerate(Integer productId, Integer totalNum) {
        Map<String, Object> map = new HashMap<>();
        OrderEntity orderEntity = new OrderEntity();
//        根据商品id查询商品信息
        ProductEntity productEntity = productMapper.findById(productId);
        orderEntity.setProductId(productId);
        orderEntity.setTotalNum(totalNum);
        orderEntity.setProductEntityName(productEntity.getName());

//        计算价格 price*totalNum=payMoney 价格*购买数量=实付金额
        BigDecimal totalNumBigDecimal = new BigDecimal(totalNum.toString());
        orderEntity.setPayMoney(totalNumBigDecimal.multiply(productEntity.getPrice()));
        map.put("order", (OrderEntity) orderEntity);
        map.put("product", (ProductEntity) productEntity);
        return map;
    }

    /**
     * 添加订单
     *
     * @param orderEntity 订单信息
     * @return int i 0失败
     */
    public int insert(OrderEntity orderEntity) {
        int i;

        //订单创建时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String createTime = sdf.format(date);
//        订单流水号
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
        String transactionId = sdf1.format(date);
        orderEntity.setTransactionId(transactionId);

//        商品id不能为空
        if (orderEntity.getProductId() != null && !orderEntity.getProductId().toString().equals("")) {
            ProductEntity productEntity = productMapper.findById(orderEntity.getProductId());
            /**
             * referPayMoney=merRatio/100*payMoney 商户支付金额=供应商分配比例/100*用户支付金额
             * wlefareMoney=referRatio/100*payMoney 商户收益金额=商户分配比例/100*用户支付金额
             * returnMoney=payMoney-referPayMoney-wlefareMoney 返利金额=用户支付金额-商户支付金额-商户收益金额
             */
            BigDecimal divide = new BigDecimal("100");
            BigDecimal referPayMoney = productEntity.getMerRatio().multiply(orderEntity.getPayMoney().divide(divide));
            BigDecimal welfareMoney = productEntity.getReferRatio().multiply(orderEntity.getPayMoney().divide(divide));
            BigDecimal returnMoney = orderEntity.getPayMoney().subtract(referPayMoney.add(welfareMoney));
            orderEntity.setReferPayMoney(referPayMoney);
            orderEntity.setWelfareMoney(welfareMoney);
            orderEntity.setReturnMoney(returnMoney);

            orderEntity.setCreateTime(createTime);//订单创建时间
            orderEntity.setUpdateTime(createTime);//订单修改时间
            orderEntity.setConsignStatus("2");//发货状态 未发货
            orderEntity.setOrderStatus("1");//订单状态 未完成
            orderEntity.setPayStatus("2");//支付状态 未支付
            orderEntity.setReferPayStatus("2");//商户支付状态 未支付
            orderEntity.setReturnMoneyStatus("1");//返利状态 未返利
            orderEntity.setIsDelete("1");//订单是否删除 未删除
            i = orderMapper.insert(orderEntity);
        } else {
            i = 0;
        }
        return i;
    }

    /**
     * 修改
     *
     * @param orderEntity 订单信息
     * @return int 修改结果 0失败
     */
    @Override
    public int update(OrderEntity orderEntity) {
        return orderMapper.update(orderEntity);
    }

    /**
     * 修改订单信息
     *
     * @param orderEntity 订单信息
     * @param operation   操作 0修改发货状态 1确认收货 2确认用户支付 3确认中间用户支付 4用户支付 5上级用户支付
     * @return 修改结果 0成功 1失败
     */
    public int update(OrderEntity orderEntity, Integer operation) {
        int i;
        if (operation == 0) {//修改发货状态
            Date date = new Date();//订单修改时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式
            String consignTime = sdf.format(date);//发货时间
            if (orderEntity.getId() != null && !orderEntity.getId().equals("")) {
                OrderEntity orderEntityNew = orderMapper.findById(orderEntity.getId());
                orderEntityNew.setShippingName(orderEntity.getShippingName());//物流名称
                orderEntityNew.setShippingCode(orderEntity.getShippingCode());//物流单号
                orderEntityNew.setConsignTime(consignTime);//发货时间
                orderEntityNew.setUpdateTime(consignTime);//修改时间
                orderEntityNew.setConsignStatus("1");//发货状态 已发货
                i = orderMapper.update(orderEntityNew);
            } else {
                i = 1;
            }
        } else if (operation == 1) {//确认收货
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String closeTime = sdf.format(date);//订单关闭时间
            if (orderEntity.getId() != null && !orderEntity.getId().equals("")) {
                orderEntity = orderMapper.findById(orderEntity.getId());
                orderEntity.setConsignStatus("0");//发货状态 已收货
                orderEntity.setUpdateTime(closeTime);
                orderEntity.setCloseTime(closeTime);
                orderEntity.setEndTime(closeTime);//订单完成时间
                orderEntity.setOrderStatus("0");//订单状态 已完成
                i = orderMapper.update(orderEntity);
            } else {
                i = 0;
            }
        } else if (operation == 2) {//确认用户支付
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String userPayTime = sdf.format(date);//确认用户支付时间
            if (orderEntity.getId() != null && !orderEntity.getId().equals("")) {
                orderEntity = orderMapper.findById(orderEntity.getId());
                orderEntity.setUpdateTime(userPayTime);
                orderEntity.setPayTime(userPayTime);//用户支付时间
//                orderEntity.setPayType(orderEntity.getUserEntityAcctType());
                orderEntity.setPayStatus("0");//用户支付状态 已支付
                i = orderMapper.update(orderEntity);
            } else {
                i = 0;
            }
        } else if (operation == 3) {//确认商户支付
            Date date = new Date();//确认商户支付时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String referPayTime = sdf.format(date);
            if (orderEntity.getId() != null && !orderEntity.getId().equals("")) {
                orderEntity = orderMapper.findById(orderEntity.getId());
                orderEntity.setUpdateTime(referPayTime);
                orderEntity.setReferPayTime(referPayTime);
                orderEntity.setReferPayStatus("0");
                i = orderMapper.update(orderEntity);
            } else {
                i = 0;
            }
        } else if (operation == 4) {
//           用户支付
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String PayTime = sdf.format(date);
            if (orderEntity.getId() != null && !orderEntity.getId().equals("")) {
                orderEntity = orderMapper.findById(orderEntity.getId());
                orderEntity.setUpdateTime(PayTime);
                orderEntity.setPayTime(PayTime);
                orderEntity.setPayStatus("1");
                orderEntity.setIsDelete("0");
                i = orderMapper.update(orderEntity);
            } else {
                i = 0;
            }
        } else if (operation == 5) {
//            上级用户支付
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String referPayTime = sdf.format(date);
            if (orderEntity.getId() != null && !orderEntity.getId().equals("")) {
                orderEntity = orderMapper.findById(orderEntity.getId());
                orderEntity.setUpdateTime(referPayTime);
                orderEntity.setReferPayTime(referPayTime);
                orderEntity.setReferPayStatus("1");
                i = orderMapper.update(orderEntity);
            } else {
                i = 0;
            }
        } else {
            i = 0;
        }
        return i;
    }

    /**
     * 删除订单（软删除）
     *
     * @param t 订单id
     * @return int 0 失败
     */
    public int deleteById(int t) {
        return orderMapper.deleteById(t);
    }


    public UserEntity findReferAccout(int id) {
////        return orderMapper.findReferAccout(id);
//        return null;
        System.out.println("***********"+id);
        UserEntity userEntity = orderMapper.findReferAccout(id);
        if (null==userEntity){
            userEntity = new UserEntity();
            userEntity.setWechatNum("");
            userEntity.setAlipayNum("");
            userEntity.setBankcardNum("");
            System.out.println("********userEntity=null");
            return userEntity;
        }else {
            System.out.println("********userEntity!=null");
            return userEntity;
        }
    }

    public MerchantEntity findMerchantEntityAccout(int id) {
        MerchantEntity merchantEntity = orderMapper.findMerchantEntityAccout(id);
        if (null==merchantEntity){
            merchantEntity = new MerchantEntity();
            merchantEntity.setAlipayNum("");
            merchantEntity.setWechatNum("");
            merchantEntity.setBankCardNum("");
            return merchantEntity;
        }else {
            return merchantEntity;
        }
    }

}
